package by.grsu.shakh.dao;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import by.grsu.shakh.entity.User;
import by.grsu.shakh.table.UserTable;

import com.epam.grsulab.webapi.dao.AbstractDao;

public class UserDao extends AbstractDao<UserTable, User> {

	public UserDao(String rootFolderPath) {
		super(rootFolderPath);
	}

	@Override
	public void saveNew(final User newUser) {
		newUser.setId(getNextId());
		final UserTable userTable = deserializeFromXml();
		userTable.getRows().add(newUser);
		serializeToXml(userTable);
	}

	@Override
	public void update(final User entity) {
		final UserTable userTable = deserializeFromXml();
		for (final User u : userTable.getRows()) {
			if (u.getId().equals(entity.getId())) {
				u.setAdress(entity.getAdress());
				u.setFirstName(entity.getFirstName());
				u.setMail(entity.getMail());
				u.setUserRole(entity.getUserRole());
				u.setSurName(entity.getSurName());
				u.setLogin(entity.getLogin());
				u.setPassword(entity.getPassword());
				break;
			}
		}
		serializeToXml(userTable);

	}

	@Override
	public User get(Serializable id) {
		final UserTable userTable = deserializeFromXml();
		for (final User u : userTable.getRows()) {
			if (u.getId().equals(id)) {
				return u;
			}
		}

		return null;
	}

	@Override
	public List<User> getAll() {
		final UserTable userTable = deserializeFromXml();
		return userTable.getRows();
	}

	@Override
	public void delete(Serializable id) {
		final UserTable userTable = deserializeFromXml();
		User toBeDeletedUser = null;
		for (final User u : userTable.getRows()) {
			if (u.getId().equals(id)) {
				toBeDeletedUser = u;
				break;
			}
		}
		userTable.getRows().remove(toBeDeletedUser);
		serializeToXml(userTable);
	}

	public List<User> searchBySurName(String surName) {
		final UserTable userTable = deserializeFromXml();
		List<User> listUsers = new ArrayList<User>();
		for (final User u : userTable.getRows()) {
			if (u.getSurName().equals(surName)) {
				listUsers.add(u);
			}
		}
		return listUsers;
	}
	public User searchByLogin(String login) {
		final UserTable userTable = deserializeFromXml();
		User user = new User();
		for (final User u : userTable.getRows()) {
			if (u.getLogin().equals(login)) {
				user=u;
				break;
			}
		}
		return user;
	}

	public List<User> searchByFirstName(String name) {
		final UserTable userTable = deserializeFromXml();
		List<User> listUsers = new ArrayList<User>();
		for (final User u : userTable.getRows()) {
			if (u.getFirstName().equals(name)) {
				listUsers.add(u);
			}
		}
		return listUsers;
	}

	@Override
	protected Class<UserTable> getTableClass() {
		return UserTable.class;
	}
}
